package com.zhongge.servlet;

import com.zhongge.entity.Student;
import com.zhongge.service.StudentService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName AddStudentServlet
 * @Description TODO
 * @Author zhongge
 * @Version 1.0
 */
@WebServlet("/add")
public class AddStudentServlet extends HttpServlet {
    StudentService studentService = new StudentService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //为了数据格式一致，设置一下字符集
        req.setCharacterEncoding("UTF-8");
        //得到前端提交的数据==》有参数获取值==》以键值对的方式提交
        String name = req.getParameter("name");
        String age = req.getParameter("age");
        String sex = req.getParameter("sex");
        String birthday = req.getParameter("birthday");
        String address = req.getParameter("address");
        String remark = req.getParameter("remark");

        //创建学生对象
        Student student = new Student();
        //设置属性
        student.setName(name);
        student.setAge(Integer.parseInt(age));
        student.setSex(Integer.parseInt(sex));
        //日期格式化
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd");
        Date date;
        try {
            date = simpleDateFormat.parse(birthday);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        student.setBirthday(date);
        student.setAddress(address);
        student.setRemark(remark);

        //将学生加入
        boolean res = studentService.addStudent(student);

        if (res) {
            //成功==》输出添加成功
            req.setAttribute("successMessage", "请返回列表查看添加信息");
            req.getRequestDispatcher("student/addResult.jsp").forward(req, resp);
        }else {
            req.setAttribute("errorMessage", "添加失败");
            req.getRequestDispatcher("student/addResult.jsp").forward(req, resp);
        }
    }
}
